using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using MacomberMap.Common.Internals;

namespace MacomberMap.Common.Convertors
{
    /// <summary>
    /// This class converts betweens strings and points
    /// </summary>
    public class MM_PointF_Converter : ExpandableObjectConverter
    {
        /// <summary>
        /// Whether a value can be converted to a PointF
        /// </summary>
        /// <param name="context"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(PointF))
                return true;
            else
                return base.CanConvertTo(context, destinationType);
        }

        /// <summary>
        /// Convert a string to a PointF
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <returns></returns>
        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(PointF) && value is PointF)
                return ((PointF)value).ToString();
            else
                return base.ConvertTo(context, culture, value, destinationType);
        }

        /// <summary>
        /// Convert from a string to PointF
        /// </summary>
        /// <param name="context"></param>
        /// <param name="culture"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is String)
                try
                {
                    string[] splStr = (value as String).Split(new char[] { '=', ',', '}' }, StringSplitOptions.RemoveEmptyEntries);
                    if (splStr.Length != 2)
                        return new PointF(float.NaN, float.NaN);
                    else
                        return new PointF(MM_Repository.ToSingle(splStr[0]), MM_Repository.ToSingle(splStr[1]));
                }
                catch
                {
                    throw new ArgumentException("Cannot convert " + (value as string) + " to a PointF!");
                }

            return base.ConvertFrom(context, culture, value);
        }
    }
}
